package javaNIO1.charSets;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.*;
/**
 * Created with Intel IDEA.
 *
 * @Auther: gjt
 * @Date: 2024/8/4 13:00
 */
public class CharSetDecodes {
    public static void main(String[] args) throws IOException {
        String charsetName = "ISO-8859-1";
        if(args.length > 0){
            charsetName = args[0];
        }
        decodeChannel(Channels.newChannel(System.in),new OutputStreamWriter(System.out),Charset.forName(charsetName));

    }


    private static void decodeChannel(ReadableByteChannel source, Writer writer, Charset charset) throws IOException {

        CharsetDecoder charsetDecoder = charset.newDecoder();
        charsetDecoder.onMalformedInput(CodingErrorAction.REPLACE);
        charsetDecoder.onUnmappableCharacter(CodingErrorAction.REPLACE);

        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(16 * 1024);
        CharBuffer charBuffer = CharBuffer.allocate(57);

        CoderResult result = CoderResult.UNDERFLOW;
        boolean eof = false;
        while(!eof){
            if(result == CoderResult.UNDERFLOW){
                byteBuffer.clear();
                eof = (source.read(byteBuffer) == -1);
                byteBuffer.flip();
            }
            result = charsetDecoder.decode(byteBuffer,charBuffer,eof);
            if(result == CoderResult.OVERFLOW){
                drainCharBuffer(charBuffer,writer);
            }
        }
        while(charsetDecoder.flush(charBuffer) == CoderResult.OVERFLOW){
            drainCharBuffer(charBuffer,writer);
        }
        drainCharBuffer(charBuffer,writer);
        source.close();
        writer.close();

    }

    // 输出字符缓冲区 到 输出流中
    private static void drainCharBuffer(CharBuffer charBuffer, Writer writer) throws IOException {
        charBuffer.flip();
        if(charBuffer.hasRemaining()){
            writer.write(charBuffer.toString());
        }
        charBuffer.clear();
    }
}
